package com.example.healthcondition.services.impl;

import com.example.healthcondition.entity.DietPlans;
import com.example.healthcondition.entity.HealthData;
import com.example.healthcondition.mapper.DietPlansMapper;
import com.example.healthcondition.mapper.HealthDataMapper;
import com.example.healthcondition.services.DietPlansService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Map;

@Service
public class DietPlansServiceImpl implements DietPlansService {

    @Autowired
    private DietPlansMapper dietPlansMapper;

    @Autowired
    private HealthDataMapper healthDataMapper;

    private static final BigDecimal HEALTHY_BMI_LOWER = new BigDecimal("18.5");
    private static final BigDecimal HEALTHY_BMI_UPPER = new BigDecimal("24.9");
    private static final int NORMAL_CALORIES = 2000;

    @Override
    public DietPlans generateDietPlan(Integer userId) {
        // 获取用户最新的健康数据
        HealthData healthData = healthDataMapper.findLatestByUserId(userId);
        if (healthData == null) {
            throw new RuntimeException("未找到用户的健康数据");
        }

        // 计算 BMI
        BigDecimal bmi = calculateBMI(healthData.getWeight(), healthData.getHeight());
        if (bmi == null) {
            throw new RuntimeException("无法计算 BMI，身高或体重数据缺失");
        }

        // 获取用户最新的饮食计划中的卡路里值
        Map<String, Object> latestDietPlan = dietPlansMapper.findLatestByUserId(userId);
        int currentCalories = (latestDietPlan != null && latestDietPlan.containsKey("daily_calories")) ?
                (int) latestDietPlan.get("daily_calories") : NORMAL_CALORIES;

        // 根据 BMI 和当前卡路里值生成饮食计划
        int dailyCalories = calculateDailyCalories(bmi, currentCalories);
        String description = generateDescription(bmi, currentCalories, dailyCalories);

        // 创建饮食计划
        DietPlans dietPlan = new DietPlans();
        dietPlan.setUserId(userId);
        dietPlan.setPlanName("个性化饮食计划");
        dietPlan.setStartDate(LocalDate.now());
        dietPlan.setEndDate(LocalDate.now().plusDays(30)); // 计划持续 30 天
        dietPlan.setDailyCalories(dailyCalories);
        dietPlan.setDescription(description);

        // 保存饮食计划到数据库
        dietPlansMapper.insertDietPlan(dietPlan);

        return dietPlan;
    }

    @Override
    public Map<String, Object> getDietPlanById(Integer planId) {
        return dietPlansMapper.findLatestByUserId(planId);
    }

    @Override
    public int insertDietPlan(DietPlans dietPlans) {
        return dietPlansMapper.insertDietPlan(dietPlans);
    }

    /**
     * 计算 BMI
     */
    private BigDecimal calculateBMI(BigDecimal weight, BigDecimal height) {
        if (weight == null || height == null || height.compareTo(BigDecimal.ZERO) == 0) {
            return null;
        }
        return weight.divide(height.pow(2), 2, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 根据 BMI 和当前卡路里值计算每日推荐卡路里
     */
    private int calculateDailyCalories(BigDecimal bmi, int currentCalories) {
        if (bmi.compareTo(HEALTHY_BMI_UPPER) > 0) { // BMI > 24.9，超重
            if (currentCalories > NORMAL_CALORIES) {
                return NORMAL_CALORIES - 300; // 减少卡路里
            } else if (currentCalories == NORMAL_CALORIES) {
                return NORMAL_CALORIES - 200; // 适当减少卡路里
            } else {
                return currentCalories; // 不需要改变
            }
        } else if (bmi.compareTo(HEALTHY_BMI_LOWER) < 0) { // BMI < 18.5，体重不足
            if (currentCalories < NORMAL_CALORIES) {
                return NORMAL_CALORIES + 300; // 增加卡路里
            } else if (currentCalories == NORMAL_CALORIES) {
                return NORMAL_CALORIES + 200; // 适当增加卡路里
            } else {
                return currentCalories; // 不需要改变
            }
        } else { // BMI 在健康范围内
            return NORMAL_CALORIES; // 保持正常卡路里摄入
        }
    }

    /**
     * 生成饮食计划描述
     */
    private String generateDescription(BigDecimal bmi, int currentCalories, int dailyCalories) {
        StringBuilder description = new StringBuilder();
        description.append("您的 BMI 为 ").append(bmi).append("。");

        if (bmi.compareTo(HEALTHY_BMI_UPPER) > 0) { // 超重
            description.append("您的体重偏高，");
            if (dailyCalories < currentCalories) {
                description.append("建议减少每日卡路里摄入至 ").append(dailyCalories).append(" 卡路里。");
            } else {
                description.append("当前饮食合理，建议保持。");
            }
        } else if (bmi.compareTo(HEALTHY_BMI_LOWER) < 0) { // 体重不足
            description.append("您的体重偏低，");
            if (dailyCalories > currentCalories) {
                description.append("建议增加每日卡路里摄入至 ").append(dailyCalories).append(" 卡路里。");
            } else {
                description.append("当前饮食合理，建议保持。");
            }
        } else { // 健康体重
            description.append("您的体重在正常范围内，建议保持每日摄入 ").append(dailyCalories).append(" 卡路里。");
        }

        return description.toString();
    }
}
